package com.xsdl.Interpreter;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class ExpressionParse {

    private static final Set<Character> operatorSet = Set.of('+', '-', '*', '/');

    private boolean isOperator(char c) {
        return operatorSet.contains(c);
    }

    public Expression parse(List<String> suffixExpressions) {
        LinkedList<Expression> stack = new LinkedList<>();
        for (String item : suffixExpressions) {
            if (isOperator(item.charAt(0))) {
                Expression right = stack.removeLast();
                switch (item) {
                    case "+": {
                        stack.add(new AddExpression(stack.removeLast(), right));
                        break;
                    }
                    case "-": {
                        stack.add(new SubExpression(stack.removeLast(), right));
                        break;
                    }
                    case "*": {
                        stack.add(new MultiplyExpression(stack.removeLast(), right));
                        break;
                    }
                    case "/": {
                        stack.add(new DivisionExpression(stack.removeLast(), right));
                        break;
                    }
                }
            } else {
                stack.addLast(new NumberExpression(Integer.parseInt(item)));
            }
        }
        return stack.getLast();
    }

}
